package com.example.hotel.blImpl.user;

import com.example.hotel.bl.user.AccountService;
import com.example.hotel.data.credit.CreditMapper;
import com.example.hotel.data.enterprise.EntMapper;
import com.example.hotel.data.user.AccountMapper;
import com.example.hotel.data.user.UserImgMapper;
import com.example.hotel.enums.CreditAction;
import com.example.hotel.po.CreditInfo;
import com.example.hotel.po.User;
import com.example.hotel.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;


@Service
public class AccountServiceImpl implements AccountService {
    private final static String ACCOUNT_EXIST = "账号已存在";
    private final static String UPDATE_ERROR = "修改失败";
    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private EntMapper entMapper;

    @Autowired
    private CreditMapper creditMapper;
    @Autowired
    private UserImgMapper userImgMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    // : 注册加密
    @Override
    public ResponseVO registerAccount(UserVO userVO) {
        User user = new User();
        BeanUtils.copyProperties(userVO,user);
        // 此处进行加密
        user.setPassword(passwordEncoder.encode(userVO.getPassword()));
        try {
            accountMapper.createNewAccount(user);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return ResponseVO.buildFailure(ACCOUNT_EXIST);
        }

        return ResponseVO.buildSuccess(user);
    }

    // : 添加密码验证
    @Override
    public User login(UserForm userForm) {
        User user = accountMapper.getAccountByName(userForm.getEmail());
        // 添加加密功能
        if (null == user || !(passwordEncoder.matches(userForm.getPassword(), user.getPassword()))) {
            return null;
        }
        return user;
    }

    @Override
    public User getUserInfo(String email) {
        User user = accountMapper.getAccountByName(email);
        return user;
    }

    // : 抹掉密码
    @Override
    public User getUserInfo(int id) {
        User user = accountMapper.getAccountById(id);
        user.setPassword(null);
        return user;
    }

    // : 添加密码验证
    @Override
    public ResponseVO updateUserInfo(int id, String password, String username, String phonenumber) {
        try {
            if (password == null || password.equals("")) {
                password = null;
            } else {
                // 加密：密码验证
                password = passwordEncoder.encode(password);
            }
            accountMapper.updateAccount(id, password, username, phonenumber);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return ResponseVO.buildFailure(UPDATE_ERROR);
        }
        return ResponseVO.buildSuccess(true);
    }

    @Override
    public ResponseVO getUserCreditInfo(int id) {
        List<CreditInfo> creditInfoByUserId = creditMapper.getCreditInfoByUserId(id);
        return ResponseVO.buildSuccess(creditInfoByUserId);
    }

    @Override
    public ResponseVO registerEntUser(UserEntVO userEntVO) {
        EntVO entVO = userEntVO.getEntVO();
        if (entMapper.validateEntUser(entVO) > 0 ) {
            // 验证通过
            User user = getUserInfo(userEntVO.getUserVO().getId());
            if (user == null) {
                return ResponseVO.buildFailure("用户不存在!");
            }
            if (entMapper.associateUserWithEnt(user.getId(), entVO.getId()) > 0)
                return ResponseVO.buildSuccess("绑定成功");
            else return ResponseVO.buildFailure("内部错误");
        } else {
            // 验证失败
            return ResponseVO.buildFailure("企业验证失败");
        }

    }

    //信用充值
    //
    @Override
    public ResponseVO investCredit(int id, double investedMoney) {
        User user = accountMapper.getAccountById(id);
        if(user==null){
            return ResponseVO.buildFailure("用户不存在");
        }
        if(user.getCredit()==null)user.setCredit(0);
        double originalCredit = user.getCredit();
        double added = investedMoney*100;
        double newCredit =added+originalCredit;
        int rowNum = accountMapper.updateAccountCredit(id,newCredit);

        //增加记录
        //TODO  action感觉应该是string类型
        CreditInfo creditInfo = new CreditInfo();
        LocalDateTime nowTime = LocalDateTime.now();
        String nowDate = nowTime.toLocalDate().toString();
        creditInfo.setAction(CreditAction.AddFrc);
        creditInfo.setTime(nowDate);//设为当前时间
        creditInfo.setOrderId(0);//TODO 测试的 之后要用
        creditInfo.setChangeVal(added);
        creditInfo.setAfterChange(newCredit);
        creditInfo.setUserId(id);
        creditMapper.addCreditInfo(creditInfo);


        return ResponseVO.buildSuccess(true);
    }

    @Override
    public ResponseVO searchUsers(UserVO userVO) {
        User user = new User();
        BeanUtils.copyProperties(userVO,user);
        List<User> users;
        try {
            users = accountMapper.searchUsers(user);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseVO.buildFailure("内部错误");
        }
        return ResponseVO.buildSuccess(users);
    }

    @Override
    public ResponseVO setAsHtlMgr(Integer id) {
        if (accountMapper.updateAsMgr(id) > 0) return ResponseVO.buildSuccess(true);
        return ResponseVO.buildFailure("新增绑定失败");
    }

    @Override
    public ResponseVO deleteUser(Integer id) {
        if(accountMapper.deleteUser(id)>0) return ResponseVO.buildSuccess(true);
        return ResponseVO.buildFailure("用户不存在");
    }

    @Override
    public ResponseVO savePic(MultipartFile file, Integer userId) {
        if(file.isEmpty()){
            return ResponseVO.buildFailure("上传失败,请选择文件");
        }

        try{
            InputStream is = file.getInputStream();
            UserImgVO userImgVO=new UserImgVO();
            userImgVO.setUserId(userId);
            byte[] pic = new byte[(int)file.getSize()];
            is.read(pic);
            userImgVO.setPic(pic);

            if(userImgMapper.getPic(userId)==null){//还没有记录,插入
                userImgMapper.insertPic(userImgVO);
            }
            else{//存在记录,更新
                userImgMapper.updatePic(userImgVO);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


        return ResponseVO.buildSuccess("上传成功");
    }

    @Override
    public ResponseVO getPic(Integer userId) {
        UserImgVO userImgVO = userImgMapper.getPic(userId);
        if (userImgVO==null)return ResponseVO.buildSuccess(null);
        return ResponseVO.buildSuccess(userImgVO);
    }

    @Override
    public Integer getIdByEmail(String email) {
        User userInfo = getUserInfo(email);
        if (userInfo != null) {
            System.out.println(email);
            System.out.println(userInfo.getId());
            return userInfo.getId();}
        return -1;
    }


    @Override
    public Integer updateAccountCredit(Integer userid, double newCredit) {
        return accountMapper.updateAccountCredit(userid, newCredit);
    }
}
